<template>
	<div class="basic-config-form">
		<a-form-item label="API基础地址" name="baseUrl" required>
			<a-input v-model:value="baseUrl" placeholder="https://api.example.com" @change="handleConfigChange" />
			<div class="form-help-text">外部API的基础URL地址</div>
		</a-form-item>

		<a-form-item label="请求超时时间" name="timeout">
			<a-input-number
				v-model:value="timeout"
				:max="300000"
				:min="1000"
				:step="1000"
				addon-after="毫秒"
				placeholder="30000"
				@change="handleConfigChange"
			/>
			<div class="form-help-text">API请求的超时时间，默认30秒</div>
		</a-form-item>

		<a-form-item label="重试次数" name="retryCount">
			<a-input-number v-model:value="retryCount" :max="10" :min="0" placeholder="3" @change="handleConfigChange" />
			<div class="form-help-text">请求失败时的重试次数</div>
		</a-form-item>
	</div>
</template>

<script setup>
	import { ref, watch } from 'vue'

	// Props
	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({})
		}
	})

	// Emits
	const emit = defineEmits(['update:modelValue', 'change'])

	// 基础配置
	const baseUrl = ref(props.modelValue.baseUrl || '')
	const timeout = ref(parseInt(props.modelValue.timeout || '30000'))
	const retryCount = ref(parseInt(props.modelValue.retryCount || '3'))

	// 监听props变化
	watch(
		() => props.modelValue,
		(newVal) => {
			if (newVal) {
				baseUrl.value = newVal.baseUrl || ''
				timeout.value = parseInt(newVal.timeout || '30000')
				retryCount.value = parseInt(newVal.retryCount || '3')
			}
		},
		{ deep: true, immediate: true }
	)

	// 更新配置
	const updateConfig = () => {
		const config = {
			baseUrl: baseUrl.value,
			timeout: timeout.value.toString(),
			retryCount: retryCount.value.toString()
		}

		emit('update:modelValue', config)
		emit('change', config)
	}

	// 处理配置变化
	const handleConfigChange = () => {
		updateConfig()
	}

	// 获取基础配置
	const getBasicConfig = () => {
		return {
			baseUrl: baseUrl.value,
			timeout: timeout.value.toString(),
			retryCount: retryCount.value.toString()
		}
	}

	// 验证配置
	const validateConfig = () => {
		if (!baseUrl.value) {
			return { valid: false, message: '请输入API基础地址' }
		}

		try {
			new URL(baseUrl.value)
		} catch (error) {
			return { valid: false, message: 'API基础地址格式不正确' }
		}

		if (timeout.value < 1000 || timeout.value > 300000) {
			return { valid: false, message: '超时时间应在1秒到5分钟之间' }
		}

		if (retryCount.value < 0 || retryCount.value > 10) {
			return { valid: false, message: '重试次数应在0到10次之间' }
		}

		return { valid: true }
	}

	// 暴露方法给父组件
	defineExpose({
		getBasicConfig,
		validateConfig
	})
</script>

<style scoped>
	.basic-config-form {
		padding: 0;
	}

	.form-help-text {
		font-size: 12px;
		color: #999;
		margin-top: 4px;
	}
</style>
